package br.com.sgmf.web.managedbean;

import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import br.com.sgmf.model.NotaFiscal;
import br.com.sgmf.service.NotaFiscalService;

import com.lowagie.text.Document;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;

@Component
@ManagedBean
@RequestScoped
public class RelatorioNotaFiscalBean {

	private static final String RELATORIO_DE_NOTAS_FISCAIS = "Relatório de Notas Fiscais";
	private static final String DATA_FIM_NAO_PODE_SER_MENOR_QUE_DATA_INICIO = "Data Fim não pode ser menor que Data Início";

	private Date inicio;
	private Date fim;

	private List<NotaFiscal> notasFiscais;

	@Autowired
	private NotaFiscalService notaFiscalService;

	@PostConstruct
	public void inicializar() {
		notasFiscais = null;
	}

	public List<NotaFiscal> buscar() {
		if (inicio != null && fim != null && fim.before(inicio)) {
			FacesContext context = FacesContext.getCurrentInstance();
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,
					DATA_FIM_NAO_PODE_SER_MENOR_QUE_DATA_INICIO, null);
			context.addMessage(null, message);
		} else {
			notasFiscais = notaFiscalService.findBetweenDate(inicio, fim);
		}
		return notasFiscais;
	}

	public void preProcessPDF(Object document) {
		Document pdf = (Document) document;
		pdf.setPageSize(PageSize.A4.rotate());
		HeaderFooter header = new HeaderFooter(new Phrase(
				RELATORIO_DE_NOTAS_FISCAIS), false);
		pdf.setHeader(header);
		pdf.open();
	}

	public Date getInicio() {
		return inicio;
	}

	public void setInicio(Date inicio) {
		this.inicio = inicio;
	}

	public Date getFim() {
		return fim;
	}

	public void setFim(Date fim) {
		this.fim = fim;
	}

	public List<NotaFiscal> getNotasFiscais() {
		return notasFiscais;
	}

	public void setNotasFiscais(List<NotaFiscal> notasFiscais) {
		this.notasFiscais = notasFiscais;
	}

	public NotaFiscalService getNotaFiscalService() {
		return notaFiscalService;
	}

	public void setNotaFiscalService(NotaFiscalService notaFiscalService) {
		this.notaFiscalService = notaFiscalService;
	}

}